package com.example.controller;

import com.example.domain.Admin;
import com.example.domain.Post;
import com.example.domain.User;
import com.example.domain.Comment;
import com.example.domain.Report;
import com.example.service.AdminService;
import com.example.service.PostService;
import com.example.service.UserService;
import com.example.service.CommentService;
import com.example.service.ReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
//处理与管理员相关的请求（如登录、管理帖子、用户、评论、举报等）
@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private PostService postService;

    @Autowired
    private UserService userService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private ReportService reportService;

    // 显示管理员登录页面（GET 请求）
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String showAdminLoginPage() {
        return "adminLogin";
    }

    // 处理管理员登录逻辑（POST 请求）
    @RequestMapping(value = "/login", method = RequestMethod.POST) // 映射到 /admin/login
    public String adminLogin(Admin admin, HttpServletRequest request) {
        try {
            Admin a = adminService.login(admin);
            if (a != null) {
                request.getSession().setAttribute("ADMIN_SESSION", a);
                return "redirect:/admin"; // 登录成功后重定向到管理员首页
            }
            request.setAttribute("msg", "管理员邮箱或密码错误");
            return "adminLogin";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "系统错误");
            return "adminLogin";
        }
    }

    // 管理员首页
    @RequestMapping("")
    public String adminHome(HttpServletRequest request) {
        // 检查管理员是否已登录
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("ADMIN_SESSION");
        if (admin == null) {
            return "redirect:/admin/login";
        }
        return "adminHome";
    }

    // 帖子管理页面
    @RequestMapping("/posts")
    public String adminPosts(@RequestParam(required = false) String keyword,
                             @RequestParam(required = false) String status,
                             HttpServletRequest request) {
        // 检查管理员是否已登录
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("ADMIN_SESSION");
        if (admin == null) {
            return "redirect:/admin/login";
        }

        try {
            // 获取所有帖子（包括被屏蔽的）
            List<Post> posts = postService.findAllForAdmin(keyword, status);

            // 为每个帖子设置用户名
            if (posts != null) {
                for (Post post : posts) {
                    if (post.getUserId() != null) {
                        User user = userService.findById(post.getUserId());
                        if (user != null) {
                            post.setUsername(user.getUsername());
                        }
                    }
                }
            }

            request.setAttribute("posts", posts);
            return "adminPosts";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "获取帖子列表失败");
            return "adminPosts";
        }
    }

    // 更新帖子状态
    @RequestMapping(value = "/updatePostStatus", method = RequestMethod.POST)
    public String updatePostStatus(@RequestParam Integer id,
                                   @RequestParam String status,
                                   HttpServletRequest request) {
        // 检查管理员是否已登录
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("ADMIN_SESSION");
        if (admin == null) {
            return "redirect:/admin/login";
        }

        try {
            postService.updateStatus(id, status);
            return "redirect:/admin/posts";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "更新帖子状态失败");
            return "redirect:/admin/posts";
        }
    }

    // 用户管理页面
    @RequestMapping("/users")
    public String adminUsers(HttpServletRequest request) {
        // 检查管理员是否已登录
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("ADMIN_SESSION");
        if (admin == null) {
            return "redirect:/admin/login";
        }

        try {
            List<User> users = userService.findAll();
            request.setAttribute("users", users);
            return "adminUsers";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "获取用户列表失败");
            return "adminUsers";
        }
    }

    // 更新用户状态
    @RequestMapping(value = "/updateUserStatus", method = RequestMethod.POST)
    public String updateUserStatus(@RequestParam Integer id,
                                   @RequestParam String status,
                                   HttpServletRequest request) {
        // 检查管理员是否已登录
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("ADMIN_SESSION");
        if (admin == null) {
            return "redirect:/admin/login";
        }

        try {
            userService.updateStatus(id, status);
            return "redirect:/admin/users";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "更新用户状态失败");
            return "redirect:/admin/users";
        }
    }

    // 评论管理页面
    @RequestMapping("/comments")
    public String adminComments(HttpServletRequest request) {
        // 检查管理员是否已登录
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("ADMIN_SESSION");
        if (admin == null) {
            return "redirect:/admin/login";
        }

        try {
            List<Comment> comments = commentService.findAllForAdmin();
            request.setAttribute("comments", comments);
            return "adminComments";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "获取评论列表失败");
            return "adminComments";
        }
    }

    // 更新评论状态
    @RequestMapping(value = "/updateCommentStatus", method = RequestMethod.POST)
    public String updateCommentStatus(@RequestParam Integer id,
                                      @RequestParam String status,
                                      HttpServletRequest request) {
        // 检查管理员是否已登录
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("ADMIN_SESSION");
        if (admin == null) {
            return "redirect:/admin/login";
        }

        try {
            commentService.updateStatus(id, status);
            return "redirect:/admin/comments";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "更新评论状态失败");
            return "redirect:/admin/comments";
        }
    }

    // 删除评论
    @RequestMapping(value = "/deleteComment", method = RequestMethod.POST)
    public String deleteComment(@RequestParam Integer id, HttpServletRequest request) {
        // 检查管理员是否已登录
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("ADMIN_SESSION");
        if (admin == null) {
            return "redirect:/admin/login";
        }

        try {
            commentService.delete(id);
            return "redirect:/admin/comments";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "删除评论失败");
            return "redirect:/admin/comments";
        }
    }

    // 举报管理页面
    @RequestMapping("/reports")
    public String adminReports(HttpServletRequest request) {
        // 检查管理员是否已登录
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("ADMIN_SESSION");
        if (admin == null) {
            return "redirect:/admin/login";
        }

        try {
            List<Report> reports = reportService.findAll();
            request.setAttribute("reports", reports);
            return "adminReports";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "获取举报列表失败");
            return "adminReports";
        }
    }

    // 更新举报状态
    @RequestMapping(value = "/updateReport", method = RequestMethod.POST)
    public String updateReport(@RequestParam Integer id,
                               @RequestParam String status,
                               HttpServletRequest request) {
        // 检查管理员是否已登录
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("ADMIN_SESSION");
        if (admin == null) {
            return "redirect:/admin/login";
        }

        try {
            reportService.updateStatus(id, status);
            return "redirect:/admin/reports";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "更新举报状态失败");
            return "redirect:/admin/reports";
        }
    }

    // 屏蔽帖子（通过举报）
    @RequestMapping(value = "/blockPost", method = RequestMethod.POST)
    public String blockPost(@RequestParam Integer id, HttpServletRequest request) {
        // 检查管理员是否已登录
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("ADMIN_SESSION");
        if (admin == null) {
            return "redirect:/admin/login";
        }

        try {
            postService.updateStatus(id, "blocked");
            return "redirect:/admin/reports";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "屏蔽帖子失败");
            return "redirect:/admin/reports";
        }
    }

    // 屏蔽评论（通过举报）
    @RequestMapping(value = "/blockComment", method = RequestMethod.POST)
    public String blockComment(@RequestParam Integer id, HttpServletRequest request) {
        // 检查管理员是否已登录
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("ADMIN_SESSION");
        if (admin == null) {
            return "redirect:/admin/login";
        }

        try {
            commentService.updateStatus(id, "blocked");
            return "redirect:/admin/reports";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "屏蔽评论失败");
            return "redirect:/admin/reports";
        }
    }

    // 管理员登出
    @RequestMapping("/logout")
    public String adminLogout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.removeAttribute("ADMIN_SESSION");
        return "redirect:/admin/login"; // 修改为重定向到管理员登录页面
    }
}